import { Injectable } from "@nestjs/common";
import { CreateUserSubuserDto } from "./dto/create-user-subuser.dto";
import { UpdateUserSubuserDto } from "./dto/update-user-subuser.dto";
import { Like, Not, Repository } from "typeorm";
import { ResultData } from "@/common/utils/result";
import { instanceToPlain } from "class-transformer";
import { InjectRepository } from "@nestjs/typeorm";
import { UserSubuser } from "@/modules/user-subuser/entities/user-subuser.entity";


@Injectable()
export class UserSubuserService {
    constructor(
        @InjectRepository(UserSubuser)
        private readonly userSubuserRepository: Repository<UserSubuser>
    ) {
    }
    
    create(createUserSubuserDto: CreateUserSubuserDto) {
        return "This action adds a new userSubuser";
    }
    
    async findAll(findAllDto) {
        const { page, size, userId } = findAllDto;
        const take = size || 15;
        const skip = ((page || 1) - 1) * take;
        const where = {
            ...(userId === 0 || userId ? { userId } : null)
        };
        return ResultData.rowOk(instanceToPlain(await this.userSubuserRepository.findAndCount({
            order: {
                id: "DESC"
            },
            where,
            relations: {
                subuser: true
            },
            skip,
            take
        })));
    }
    
    findOne(id: number) {
        return `This action returns a #${id} userSubuser`;
    }
    
    update(id: number, updateUserSubuserDto: UpdateUserSubuserDto) {
        return `This action updates a #${id} userSubuser`;
    }
    
    remove(id: number) {
        return `This action removes a #${id} userSubuser`;
    }
    
    //给用户添加角色
    async userAddSubUser({ userIds, userId }) {
        // 删除所有再新增
        await this.userSubuserRepository.delete({ userId });
        return ResultData.ok(
            await this.userSubuserRepository.save(
                userIds.map(v => ({ userId: userId, subuserId: v }))
            )
        );
    }
    
    async getSubUserIdByUserId({ userId }) {
        const res = await this.userSubuserRepository.find(
            { where: { userId, subuserId: Not(userId) } }
        );
        return ResultData.ok(
            res.map(v => v.subuserId)
        );
    }
    
    async getSubUserInfo({ user }) {
        const res = await this.userSubuserRepository.find(
            {
                where: {
                    userId: user.id
                    // subuserId: Not(user.id)
                },
                relations: ["subuser"]
            }
        );
        return ResultData.ok(
            [user, ...res.map(v => v.subuser)]
        );
    }
    
}
